package com.yichen.codesandbox.utils;

import cn.hutool.core.util.StrUtil;
import com.yichen.codesandbox.constant.OperationType;
import com.yichen.codesandbox.model.dto.ExecutionMessage;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author: yichenwu
 * @Date:2024/6/25 14:06
 */

/**
 * 代码沙箱执行、编译
 */
public class ProcessUtils {
    private static final String SECURITY_MANAGER_PATH = "E:\\IdeaProject\\ycOJ-code-sandbox\\src\\main\\resources\\security";
    private static final String SECURITY_MANAGER_NAME = "DefaultSecurityManager";

    /**
     * 编译
     *
     * @param userCodeFile
     * @return
     */
    public static ExecutionMessage processCompile(File userCodeFile) {
        try {
            String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
            Process process = Runtime.getRuntime().exec(compileCmd);
            ExecutionMessage executionMessage = getExecutionMessage(process,OperationType.COMPILE);
            return executionMessage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 运行
     *
     * @param input
     * @return
     */
    public static ExecutionMessage processRun(String input, String userCodeParentPath) {
        try {
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, input);
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath,SECURITY_MANAGER_PATH,SECURITY_MANAGER_NAME, input);
            Process process = Runtime.getRuntime().exec(runCmd);
            // 1. 超时控制
            new Thread(() ->
            {
                try {
                    Thread.sleep(5 * 1000L);
                    process.destroy();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("超时了，守护线程开始保护");
            }).start();
            ExecutionMessage executionMessage = getExecutionMessage(process,OperationType.RUN);
            return executionMessage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static ExecutionMessage getExecutionMessage(Process process,String type) {
        ExecutionMessage executionMessage = new ExecutionMessage();
        try {
            // 等待程序执行，获取错误码
            int exitValue = process.waitFor();
            executionMessage.setExitValue(exitValue);
            // 正常退出
            if (exitValue == 0) {
                String message = type.equals(OperationType.COMPILE) ? "编译成功！！！" : "运行成功！！！";
                System.out.println(message);
                // 获取正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder compileOutPutStringBuild = new StringBuilder();
                // 逐行读取
                String readLine;
                while ((readLine = bufferedReader.readLine()) != null) {
                    compileOutPutStringBuild.append(readLine);
                }
                System.out.println(compileOutPutStringBuild);
                executionMessage.setExecuteMessage(compileOutPutStringBuild.toString());
            } else {
                // 异常退出
                String message = type.equals(OperationType.COMPILE) ? "编译失败！！！" : "运行失败！！！";
                System.out.println(message + "，错误码为：" + exitValue);
                // 获取正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder compileOutPutStringBuild = new StringBuilder();
                // 逐行读取
                String readLine;
                while ((readLine = bufferedReader.readLine()) != null) {
                    compileOutPutStringBuild.append(readLine);
                }
                System.out.println(compileOutPutStringBuild);
                executionMessage.setExecuteMessage(compileOutPutStringBuild.toString());

                // 获取异常输出
                BufferedReader bufferedErrorReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
                StringBuilder compileErrorOutPutStringBuild = new StringBuilder();
                // 逐行读取
                while ((readLine = bufferedErrorReader.readLine()) != null) {
                    compileErrorOutPutStringBuild.append(readLine);
                }
                System.out.println(compileErrorOutPutStringBuild);
                executionMessage.setExecuteErrorMessage(compileErrorOutPutStringBuild.toString());
            }
            System.out.println(executionMessage);
            return executionMessage;
        } catch (InterruptedException | IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 交互式运行（需要用户从控制台输入测试用例）
     *
     * @param input
     * @return
     */
    public static ExecutionMessage processInteractRun(String input, String userCodeParentPath) {
        ExecutionMessage executionMessage = new ExecutionMessage();
        try {
            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, input);
            Process process = Runtime.getRuntime().exec(runCmd);

            // 向控制台输入程序
            OutputStream outputStream = process.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            // 回车拼接字符，否则无法识别
            String[] split = input.split(" ");
            String inputStr = StrUtil.join("\n", split) + "\n";
            outputStreamWriter.write(inputStr);
            // 相当于回车，执行输入程序
            outputStreamWriter.flush();

            // 获取正常输出
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder compileOutPutStringBuild = new StringBuilder();
            // 逐行读取
            String readLine;
            while ((readLine = bufferedReader.readLine()) != null) {
                compileOutPutStringBuild.append(readLine);
            }
            System.out.println(compileOutPutStringBuild);
            executionMessage.setExecuteMessage(compileOutPutStringBuild.toString());

            // 记得关闭资源，否则会卡死
            bufferedReader.close();
            inputStreamReader.close();
            outputStreamWriter.close();
            outputStream.close();
            process.destroy();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return executionMessage;
    }
}
